/**
 * 模型配置管理页面组件
 * 
 * 功能特性：
 * - 模型配置列表展示和分页
 * - 支持多种AI服务提供商
 * - 创建、编辑、删除模型配置
 * - 配置激活/禁用状态管理
 * - 配置测试和验证
 * - 完整的表单验证
 * - 响应式设计支持
 * 
 * @author CKY Agent Platform Team
 * @version 1.0.0
 * @lastModified 2024-01-15
 */

import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Card,
  Modal,
  Form,
  Input,
  Select,
  Radio,
  InputNumber,
  Switch,
  message,
  Popconfirm,
  Alert,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ReloadOutlined,
  ApiOutlined,
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import agentService from '@services/agentService';

const { Option } = Select;
const { TextArea } = Input;
const { Group: RadioGroup } = Radio;

interface ModelConfig {
  id: string;
  name: string;
  provider: string;
  model: string;
  apiKey?: string;
  apiEndpoint?: string;
  maxTokens: number;
  temperature: number;
  maxConcurrency?: number;
  costPer1kTokens?: number;
  isActive: boolean;
  createdAt: string;
  lastUsedAt?: string;
}

interface CreateModelConfigDto {
  name: string;
  provider: string;
  model: string;
  apiKey?: string;
  apiEndpoint?: string;
  maxTokens: number;
  temperature: number;
  maxConcurrency?: number;
  costPer1kTokens?: number;
  isActive?: boolean;
}

interface ModelConfigStats {
  totalCount: number;
  activeCount: number;
  totalUsage: number;
  averageCost: number;
}

const providers = [
  { value: 'OpenAI', label: 'OpenAI', models: ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo'] },
  { value: 'Azure', label: 'Azure OpenAI', models: ['gpt-4', 'gpt-35-turbo'] },
  { value: 'Anthropic', label: 'Anthropic', models: ['claude-3-opus', 'claude-3-sonnet', 'claude-3-haiku'] },
  { value: 'Google', label: 'Google AI', models: ['gemini-pro', 'gemini-pro-vision'] },
  { value: '百度', label: '百度文心一言', models: ['ERNIE-Bot', 'ERNIE-Bot-turbo'] },
  { value: '阿里云', label: '阿里云通义千问', models: ['qwen-turbo', 'qwen-plus', 'qwen-max'] },
  { value: '腾讯云', label: '腾讯云混元', models: ['hunyuan-pro', 'hunyuan-lite'] },
  { value: '字节跳动', label: '字节跳动豆包', models: ['doubao-pro', 'doubao-lite'] },
];

const ModelConfigList: React.FC = () => {
  const [configs, setConfigs] = useState<ModelConfig[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [testLoading, setTestLoading] = useState<string | null>(null);
  const [form] = Form.useForm<CreateModelConfigDto>();
  const [editingConfig, setEditingConfig] = useState<ModelConfig | null>(null);
  const [stats, setStats] = useState<ModelConfigStats | null>(null);
  const [selectedProvider, setSelectedProvider] = useState<string>('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  useEffect(() => {
    loadConfigs();
    loadStats();
  }, [pagination.current, pagination.pageSize]);

  const loadConfigs = async () => {
    try {
      setLoading(true);
      const response = await agentService.getModelConfigs({
        skipCount: (pagination.current - 1) * pagination.pageSize,
        maxResultCount: pagination.pageSize,
      });
      
      setConfigs(response.items);
      setPagination(prev => ({
        ...prev,
        total: response.totalCount,
      }));
    } catch (error) {
      message.error('加载模型配置失败');
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      // 这里可以调用统计API，目前使用模拟数据
      setStats({
        totalCount: configs.length,
        activeCount: configs.filter(c => c.isActive).length,
        totalUsage: 0,
        averageCost: 0
      });
    } catch (error) {
      console.error('加载统计失败:', error);
    }
  };

  const handleCreate = () => {
    setEditingConfig(null);
    form.resetFields();
    setSelectedProvider('');
    setModalVisible(true);
  };

  const handleEdit = (config: ModelConfig) => {
    setEditingConfig(config);
    form.setFieldsValue({
      name: config.name,
      provider: config.provider,
      model: config.model,
      apiEndpoint: config.apiEndpoint,
      maxTokens: config.maxTokens,
      temperature: config.temperature,
      maxConcurrency: config.maxConcurrency,
      costPer1kTokens: config.costPer1kTokens,
      isActive: config.isActive
    });
    setSelectedProvider(config.provider);
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await agentService.deleteModelConfig(id);
      message.success('删除成功');
      loadConfigs();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      setModalLoading(true);
      
      if (editingConfig) {
        await agentService.updateModelConfig(editingConfig.id, values);
        message.success('更新成功');
      } else {
        await agentService.createModelConfig(values);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      loadConfigs();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setModalLoading(false);
    }
  };

  const handleToggleActive = async (id: string, isActive: boolean) => {
    try {
      if (isActive) {
        await agentService.deactivateModelConfig(id);
        message.success('禁用成功');
      } else {
        await agentService.activateModelConfig(id);
        message.success('激活成功');
      }
      loadConfigs();
    } catch (error) {
      message.error(isActive ? '禁用失败' : '激活失败');
    }
  };

  const handleTestConnection = async (config: ModelConfig) => {
    try {
      setTestLoading(config.id);
      // 这里可以实现连接测试逻辑
      await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟测试
      message.success('连接测试成功');
    } catch (error) {
      message.error('连接测试失败');
    } finally {
      setTestLoading(null);
    }
  };

  const handleProviderChange = (provider: string) => {
    setSelectedProvider(provider);
    form.setFieldsValue({ model: undefined });
  };

  const getProviderModels = () => {
    const provider = providers.find(p => p.value === selectedProvider);
    return provider?.models || [];
  };

  const getProviderColor = (provider: string) => {
    const colors: { [key: string]: string } = {
      'OpenAI': 'green',
      'Azure': 'blue',
      'Anthropic': 'purple',
      'Google': 'orange',
      '百度': 'red',
      '阿里云': 'cyan',
      '腾讯云': 'geekblue',
      '字节跳动': 'gold'
    };
    return colors[provider] || 'default';
  };

  const columns: ColumnsType<ModelConfig> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space direction="vertical" size="small">
          <strong>{text}</strong>
          <Tag color={getProviderColor(record.provider)}>
            {record.provider}
          </Tag>
        </Space>
      ),
    },
    {
      title: '模型信息',
      dataIndex: 'model',
      key: 'model',
      render: (text, record) => (
        <Space direction="vertical" size="small">
          <span>{text}</span>
          <span style={{ fontSize: '12px', color: '#666' }}>
            {record.maxTokens} tokens · {record.temperature} temp
          </span>
        </Space>
      ),
    },
    {
      title: 'API端点',
      dataIndex: 'apiEndpoint',
      key: 'apiEndpoint',
      ellipsis: true,
      render: (text) => text ? (
        <Tooltip title={text}>
          <span style={{ fontSize: '12px' }}>{text}</span>
        </Tooltip>
      ) : '-',
    },
    {
      title: '并发数',
      dataIndex: 'maxConcurrency',
      key: 'maxConcurrency',
      render: (text) => text || '-',
    },
    {
      title: '成本',
      dataIndex: 'costPer1kTokens',
      key: 'costPer1kTokens',
      render: (text) => text ? `$${text}/1k` : '-',
    },
    {
      title: '状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive, record) => (
        <Badge 
          status={isActive ? 'success' : 'error'} 
          text={isActive ? '激活' : '禁用'} 
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="测试连接">
            <Button 
              type="link" 
              size="small" 
              icon={<ApiOutlined />}
              loading={testLoading === record.id}
              onClick={() => handleTestConnection(record)}
            />
          </Tooltip>
          
          <Tooltip title="编辑">
            <Button 
              type="link" 
              size="small" 
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          
          <Tooltip title={record.isActive ? '禁用' : '激活'}>
            <Button 
              type="link" 
              size="small" 
              icon={record.isActive ? <CloseOutlined /> : <CheckOutlined />}
              onClick={() => handleToggleActive(record.id, record.isActive)}
            />
          </Tooltip>
          
          <Tooltip title="删除">
            <Popconfirm
              title="确定要删除这个配置吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                size="small" 
                danger 
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总配置数"
              value={stats?.totalCount || 0}
              prefix={<ApiOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="激活配置"
              value={stats?.activeCount || 0}
              prefix={<CheckOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总使用次数"
              value={stats?.totalUsage || 0}
              prefix={<EyeOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均成本"
              value={stats?.averageCost || 0}
              precision={3}
              prefix={<SettingOutlined />}
              suffix="/1k tokens"
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="模型配置管理"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={loadConfigs}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              创建配置
            </Button>
          </Space>
        }
      >
        <Alert
          message="模型配置管理"
          description="管理各种AI模型的API配置，包括OpenAI、Anthropic、Google等主流服务提供商。配置完成后可在智能体创建时选择使用。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <Table
          columns={columns}
          dataSource={configs}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize || prev.pageSize,
              }));
            },
          }}
        />
      </Card>

      <Modal
        title={editingConfig ? '编辑模型配置' : '创建模型配置'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        confirmLoading={modalLoading}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="配置名称"
                rules={[
                  { required: true, message: '请输入配置名称' },
                  { min: 2, max: 50, message: '名称长度在2-50个字符之间' }
                ]}
              >
                <Input placeholder="请输入配置名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="provider"
                label="提供商"
                rules={[{ required: true, message: '请选择提供商' }]}
              >
                <Select 
                  placeholder="请选择提供商"
                  onChange={handleProviderChange}
                >
                  {providers.map(provider => (
                    <Option key={provider.value} value={provider.value}>
                      <Tag color={getProviderColor(provider.value)}>
                        {provider.label}
                      </Tag>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="model"
                label="模型"
                rules={[{ required: true, message: '请选择模型' }]}
              >
                <Select placeholder="请选择模型">
                  {getProviderModels().map(model => (
                    <Option key={model} value={model}>
                      {model}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="apiEndpoint"
                label="API端点"
                rules={[{ required: false, message: '请输入API端点' }]}
              >
                <Input placeholder="可选：自定义API端点" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="apiKey"
            label="API密钥"
            rules={[{ required: true, message: '请输入API密钥' }]}
          >
            <Input.Password placeholder="请输入API密钥" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="maxTokens"
                label="最大令牌数"
                rules={[
                  { required: true, message: '请输入最大令牌数' },
                  { type: 'number', min: 1, max: 32000, message: '令牌数在1-32000之间' }
                ]}
              >
                <InputNumber 
                  min={1} 
                  max={32000}
                  style={{ width: '100%' }}
                  placeholder="最大令牌数"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="temperature"
                label="温度"
                rules={[
                  { required: true, message: '请输入温度值' },
                  { type: 'number', min: 0, max: 2, message: '温度值在0-2之间' }
                ]}
              >
                <InputNumber 
                  min={0} 
                  max={2}
                  step={0.1}
                  style={{ width: '100%' }}
                  placeholder="0.0-2.0"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="maxConcurrency"
                label="最大并发数"
                rules={[
                  { required: false, message: '请输入最大并发数' },
                  { type: 'number', min: 1, max: 100, message: '并发数在1-100之间' }
                ]}
              >
                <InputNumber 
                  min={1} 
                  max={100}
                  style={{ width: '100%' }}
                  placeholder="最大并发数"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="costPer1kTokens"
                label="每千令牌成本 (USD)"
                rules={[
                  { required: false, message: '请输入成本' },
                  { type: 'number', min: 0, message: '成本不能为负数' }
                ]}
              >
                <InputNumber 
                  min={0} 
                  step={0.001}
                  style={{ width: '100%' }}
                  placeholder="0.001"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="isActive"
                label="激活状态"
                valuePropName="checked"
                initialValue={true}
              >
                <Switch checkedChildren="激活" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default ModelConfigList;